package com.xinghai.system.service.impl;


import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.xinghai.common.exception.ServiceException;
import com.xinghai.common.exception.user.UserNotExistsException;
import com.xinghai.common.utils.DateUtils;

import com.xinghai.common.utils.bean.BeanUtils;
import com.xinghai.common.utils.uuid.IdUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.RechargePointsDTO;
import com.xinghai.system.domain.entity.RegisterDTO;
import com.xinghai.system.domain.entity.UpdateSuperDTO;
import com.xinghai.system.mapper.QdStoreMapper;
import com.xinghai.system.mapper.QdUserLinkMapper;
import com.xinghai.system.mapper.QdUserWalletMapper;
import com.xinghai.system.service.IQdUserPointsLogService;
import com.xinghai.system.service.IQdUserWalletService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdUserMapper;
import com.xinghai.system.service.IQdUserService;

import javax.annotation.Resource;

/**
 * 用户Service业务层处理
 *
 * @author xinghai
 * @date 2024-12-04
 */
@Service
public class QdUserServiceImpl extends ServiceImpl<QdUserMapper, QdUser>
        implements IQdUserService
{

    @Resource
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private QdUserLinkMapper userLinkMapper;
    @Resource
    private QdUserWalletMapper walletMapper;
    @Resource
    private QdStoreMapper storeMapper;

    @Autowired
    private IQdUserWalletService walletService;
    /**
     * 查询用户列表
     *
     * @param qdUser 用户
     * @return 用户集合
     */
    @Override
    public List<QdUser> list(QdUser qdUser) {
        QueryWrapper<QdUser> queryWrapper = new QueryWrapper<>();
        if (qdUser.getStatus()!= null  && !qdUser.getStatus().isEmpty()){
            queryWrapper.eq("status", qdUser.getStatus());
        }
        if (qdUser.getParams().get("beginCreateTime")!= null && !"".equals(qdUser.getParams().get("beginCreateTime"))
        &&qdUser.getParams().get("endCreateTime")!= null && !"".equals(qdUser.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdUser.getParams().get("beginCreateTime"),qdUser.getParams().get("endCreateTime"));
        }
        if (qdUser.getNickName()!= null  && !qdUser.getNickName().isEmpty()){
            queryWrapper.like("nick_name", qdUser.getNickName());
        }
        if (qdUser.getUserPhone()!= null  && !qdUser.getUserPhone().isEmpty()){
            queryWrapper.like("user_phone", qdUser.getUserPhone());
        }
        if (qdUser.getBankInfo()!= null  && !qdUser.getBankInfo().isEmpty()){
            queryWrapper.like("bank_info", qdUser.getBankInfo());
        }
        if (qdUser.getBankNo()!= null  && !qdUser.getBankNo().isEmpty()){
            queryWrapper.like("bank_no", qdUser.getBankNo());
        }
        if (qdUser.getBankName()!= null  && !qdUser.getBankName().isEmpty()){
            queryWrapper.like("bank_name", qdUser.getBankName());
        }
        if (qdUser.getUserType()!= null  && !qdUser.getUserType().isEmpty()){
            queryWrapper.eq("user_type", qdUser.getUserType());
        }
        if (qdUser.getPowerStatus()!= null  && !qdUser.getPowerStatus().isEmpty()){
            queryWrapper.eq("power_status", qdUser.getPowerStatus());
        }
        if (qdUser.getSuperId()!= null){
            queryWrapper.eq("super_id", qdUser.getSuperId());
        }
        if (qdUser.getGroupOnePower()!= null  && !qdUser.getGroupOnePower().isEmpty()){
            queryWrapper.eq("group_one_power", qdUser.getGroupOnePower());
        }
        if (qdUser.getGroupTwoPower()!= null  && !qdUser.getGroupTwoPower().isEmpty()){
            queryWrapper.eq("group_two_power", qdUser.getGroupTwoPower());
        }
        if (qdUser.getGroupThreePower()!= null  && !qdUser.getGroupThreePower().isEmpty()){
            queryWrapper.eq("group_three_power", qdUser.getGroupThreePower());
        }
        if (qdUser.getAutoStatus()!= null  && !qdUser.getAutoStatus().isEmpty()){
            queryWrapper.eq("auto_status", qdUser.getAutoStatus());
        }
        if (qdUser.getAllAmountStatus()!= null  && !qdUser.getAllAmountStatus().isEmpty()){
            queryWrapper.eq("all_amount_status", qdUser.getAllAmountStatus());
        }
        if (qdUser.getSendStatus()!= null  && !qdUser.getSendStatus().isEmpty()){
            queryWrapper.eq("send_status", qdUser.getSendStatus());
        }
        if (qdUser.getAscriptionStore()!= null){
            queryWrapper.eq("ascription_store", qdUser.getAscriptionStore());
        }
        if (qdUser.getStoreName()!= null  && !qdUser.getStoreName().isEmpty()){
            queryWrapper.like("store_name", qdUser.getStoreName());
        }
        if (qdUser.getStoreLeader()!= null  && !qdUser.getStoreLeader().isEmpty()){
            queryWrapper.like("store_leader", qdUser.getStoreLeader());
        }
        if (qdUser.getStoreLeaderPhone()!= null  && !qdUser.getStoreLeaderPhone().isEmpty()){
            queryWrapper.like("store_leader_phone", qdUser.getStoreLeaderPhone());
        }
        if (qdUser.getUserIds()!= null  && !qdUser.getUserIds().isEmpty()){
            queryWrapper.apply("FIND_IN_SET(id,'"+qdUser.getUserIds()+"')");
        }
        if (qdUser.getSearchValue()!= null  && !qdUser.getSearchValue().isEmpty()){
            queryWrapper.and(m->m.like("nick_name", qdUser.getSearchValue())
                    .or().like("user_phone", qdUser.getSearchValue())
                    .or().like("super_user_name", qdUser.getSearchValue())
                    .or().like("super_user_phone", qdUser.getSearchValue())
            );
        }
        queryWrapper.eq("del_flag","0");
        return this.list(queryWrapper);
    }

    /**
     * 删除用户信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdUser qdUser = new QdUser();
            qdUser.setId(id);
            qdUser.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdUser);
        }
        return this.removeById(id);
    }

    @Override
    public QdUser getByLoginId(Serializable id) {
        QdUser user = this.getById(id);
        if (user == null){
            throw new UserNotExistsException();
        }
        return user;
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdUser> collect = Arrays.stream(ids).map(m -> {
                QdUser qdUser = new QdUser();
                qdUser.setId(m);
                qdUser.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdUser;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入用户信息
     *
     * @param list 用户信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdUser> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdUserMapper qdUserMapper = sqlSession.getMapper(QdUserMapper.class);
            list.forEach(qdUserMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public QdUser getByUserPhone(String userPhone) {
        QueryWrapper<QdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone",userPhone);
        queryWrapper.eq("del_flag","0");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public QdUser getByInviteCode(String inviteCode) {
        QueryWrapper<QdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invite_code",inviteCode);
        queryWrapper.eq("del_flag","0");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public boolean registerUser(RegisterDTO register) {
        QdUser user = new QdUser();
        //组装参数
        BeanUtils.copyBeanProp(user,register);
        QdUser inUser = this.getByInviteCode(register.getInviteCode());
        if (inUser==null){
            throw new ServiceException("邀请码无效，请重新扫码！");
        }
        Long ascriptionStore = inUser.getAscriptionStore();
        QdStore store = storeMapper.selectById(ascriptionStore);
        if (store == null){
            throw new ServiceException("店铺异常，请联系店长！");
        }
        if (inUser!=null){
            user.setGiftValue(inUser.getGiftValue());
            user.setSuperId(inUser.getId());
            user.setSuperAvatar(inUser.getAvatar());
            user.setSuperUserName(inUser.getNickName());
            user.setSuperUserPhone(inUser.getUserPhone());
            user.setStoreLeader(inUser.getStoreLeader());
            user.setStoreName(inUser.getStoreName());
            user.setStoreLeaderId(inUser.getStoreLeaderId());
            user.setStoreLeaderImg(inUser.getStoreLeaderImg());
            user.setStoreLeaderPhone(inUser.getStoreLeaderPhone());
            user.setAscriptionStore(inUser.getAscriptionStore());
            List<QdUser> qdUserList = this.baseMapper.getAllParentMemberById(String.valueOf(inUser.getId()));
            String collect = qdUserList.stream().map(m -> String.valueOf(m.getId())).collect(Collectors.joining(","));
            this.baseMapper.updatePushNum(String.valueOf(inUser.getId()), 1);
            this.baseMapper.updateTeamNum(collect, 1);
        }
        user.setUserType("1");
        user.setUserNotice("");
        user.setNickName(register.getBankInfo());
        user.setAvatar("https://img1.baidu.com/it/u=3200425930,2413475553&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800");
        user.setInviteCode(IdUtils.randomNanoIdId());
        user.setPushNum(0);
        user.setTeamNum(1);
        user.setPowerStatus("0");
        user.setGroupOnePower("1");
        user.setGroupTwoPower("1");
        user.setGroupThreePower("1");
        user.setAutoStatus("0");
        user.setAllAmountStatus("0");
        user.setAmountQuota(new BigDecimal("0"));
        save(user);
        QdUserLink qdUserLink = new QdUserLink();
        qdUserLink.setUserId(user.getId());
        qdUserLink.setLinkUserId(user.getId());
        this.userLinkMapper.insert(qdUserLink);
        QdUserWallet wallet = new QdUserWallet();
        wallet.setUserId(user.getId());
        wallet.setUserPhone(user.getUserPhone());
        wallet.setUserName(user.getNickName());
        walletMapper.insert(wallet);
        // 250126 注册赠送积分
        if (store.getRegisterPoints().compareTo(BigDecimal.ZERO)>0){
//            wallet.setPoints(store.getRegisterPoints());
            RechargePointsDTO dto = new RechargePointsDTO();
            dto.setPoints(store.getRegisterPoints());
            dto.setUserId(String.valueOf(user.getId()));
            dto.setDetail("注册赠送积分");
            dto.setType("0");
            walletService.rechargePoints(dto);
        }
        return true;
    }

    @Override
    public String queryAllChild(String userId) {
        return baseMapper.queryAllChild(userId);
    }

    @Override
    public List<QdUser> getAllParentMemberById(String userId) {
        return this.baseMapper.getAllParentMemberById(userId);
    }
    @Override
    public boolean updateTeamNum(String userId,int num) {
        return this.baseMapper.updateTeamNum(userId,num);
    }

    @Override
    @Transactional
    public boolean updateSuperInfo(UpdateSuperDTO dto) {
        QdUser superUser = getByUserPhone(dto.getUserPhone());
        if (superUser==null){
            throw new ServiceException("推荐人填写错误");
        }
        if (superUser.getId() == dto.getUserId()){
            throw new ServiceException("不能推荐自己");
        }
        QdUser user = getById(dto.getUserId());
        if (user==null){
            throw new ServiceException("当前会员状态异常");
        }
        String s = queryAllChild(String.valueOf(dto.getUserId()));
        String[] split = s.split(",");
        for (String s1 : split){
            if (s1.equals(String.valueOf(superUser.getId()))){
                throw new ServiceException("不能设置推荐为自己的下级");
            }
        }
        QdUser newUser = new QdUser();
        newUser.setId(dto.getUserId());
        newUser.setSuperId(superUser.getId());
        newUser.setSuperAvatar(superUser.getAvatar());
        newUser.setSuperUserName(superUser.getNickName());
        newUser.setSuperUserPhone(superUser.getUserPhone());
        //新团队上级团队信息
        List<QdUser> allParentMemberById = getAllParentMemberById(String.valueOf(superUser.getId()));
        String collect = allParentMemberById.stream().map(m -> String.valueOf(m.getId())).collect(Collectors.joining(","));

        //老团队上级团队信息
        List<QdUser> oldParentMemberById = getAllParentMemberById(String.valueOf(user.getSuperId()));
        String oldCollect = oldParentMemberById.stream().map(m -> String.valueOf(m.getId())).collect(Collectors.joining(","));
        //老推荐人减少团队信息
        if (user.getSuperId()!=null){
            this.baseMapper.updateTeamNum(oldCollect,-user.getTeamNum());
            this.baseMapper.updatePushNum(String.valueOf(user.getSuperId()),-1);
        }
        //新推荐人同步团队信息
        this.baseMapper.updatePushNum(String.valueOf(superUser.getId()), 1);
        this.baseMapper.updateTeamNum(collect, user.getTeamNum());
        return updateById(newUser);
    }

    @Override
    @Transactional
    public boolean saveInfo(QdUser user) {
        if (user.getSuperId()!=null){
            List<QdUser> qdUserList = this.baseMapper.getAllParentMemberById(String.valueOf(user.getSuperId()));
            String collect = qdUserList.stream().map(m -> String.valueOf(m.getId())).collect(Collectors.joining(","));
            this.baseMapper.updatePushNum(String.valueOf(user.getSuperId()), 1);
            this.baseMapper.updateTeamNum(collect, 1);
        }
        save(user);
        QdUserLink qdUserLink = new QdUserLink();
        qdUserLink.setUserId(user.getId());
        qdUserLink.setLinkUserId(user.getId());
        userLinkMapper.insert(qdUserLink);
        QdUserWallet wallet = new QdUserWallet();
        wallet.setUserId(user.getId());
        wallet.setUserPhone(user.getUserPhone());
        wallet.setUserName(user.getNickName());
        walletMapper.insert(wallet);
        return true;
    }

    @Override
    public boolean updatePushNum(String userId,int num) {
        return this.baseMapper.updatePushNum(userId,num);
    }
}
